package com.example.carrierapp.util;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;

import com.example.carrierapp.ui.dialog.MAlertDialog;
import com.example.lb.fingerdemo.R;

/**
 * @author devin
 *         Created by devin on 2018/1/18.
 */
public class PermisstionHandleUtil {
    public static final int ACTIVITY_RESULT_CODE = 14001;

    /**
     * 处理请求权限失败的情况。 需要在{@link Activity#onActivityResult(int, int, Intent)}验证用户手动修改权限返回处理
     *
     * @param activity   当前申请权限的activity
     * @param permission 被拒绝的权限
     * @param neverAsk   是否 勾选了不在询问
     * @param listener   用户选择事件监听 which==POSITIVE_BUTTION 重新请求权限 NAGATIVE_BUTTION 选择了取消
     */
    public static void handlePermissionDenied(Activity activity, String permission, boolean neverAsk, DialogInterface
            .OnClickListener listener) {
        CharSequence message = null;
        switch (permission) {
            case Manifest.permission.READ_EXTERNAL_STORAGE:
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                message = neverAsk ? activity.getString(R.string.tip_permission_storage)
                        : activity.getString(R.string.tip_permission_storage_noask);
                break;
            case Manifest.permission.ACCESS_FINE_LOCATION:
            case Manifest.permission.READ_PHONE_STATE:
                message = activity.getString(R.string.perm_denied_tip, activity.getString(R.string.app_name));
                break;
            default:
        }
        if (message != null) {
            new MAlertDialog.Builder(activity).setMessage(message).setPositiveButton(neverAsk ? R.string
                    .setting : android.R.string.yes, (dialog, which) -> {
                if (neverAsk) {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    try {
                        intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
                        activity.startActivityForResult(intent, ACTIVITY_RESULT_CODE);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    listener.onClick(dialog, which);
                }
            }).setPositiveTextColor(R.color.color_rose_red).setTitle(R.string.title_permission)
                    .setNegativeButton(android.R.string.no, listener)
                    .show();
        }
    }
}
